#include "db_mgr.h"

#include <sstream>

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>
#include <cppconn/metadata.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/statement.h>
#include <mysql_driver.h>
#include <mysql_connection.h>

#include <common/log/log.h>

#include "base/db_server_connection.h"

DBMgr::DBMgr()
{
   dbConn_ = std::make_shared<DbServerConnection>();
}

DBMgr::~DBMgr()
{
}

bool DBMgr::init()
{
    if (!dbConn_->init())
    {
        LOG_ERROR("db server connection init failed.");
        return false;
    }

    if (!cfg_.init())
    {
        LOG_ERROR("DB CONFIG INIT FAILED.");
        return false;
    }
    try
    {
        sql::Driver * driver = sql::mysql::get_driver_instance();
        if (!driver)
        {
            LOG_ERROR("get_mysql_driver_instance FAILED.");
            return false;
        }
        const DBConfigInfo& dbInfo = cfg_.getDBInfo();
        std::stringstream ss;
        ss << dbInfo.addr << ":" << dbInfo.port;
        mysqlConn_.reset(driver->connect(ss.str().c_str(), dbInfo.user.c_str(), dbInfo.passwd.c_str()));
        if (!mysqlConn_)
        {
            LOG_ERROR("No sql connected.");
            return false;
        }
        mysqlConn_->setSchema(dbInfo.dbname);
        return true;
    }
    catch (sql::SQLException &e)
    {
        LOG_ERROR("# ERR: " << e.what()
                  << " (MySQL error code: " << e.getErrorCode()
                  << ", SQLState: " << e.getSQLState() << " )");
        return false;
    }
    return true;
}
